<template>
    <div class="row ant-bg">
        <div class="col-7">
            <el-form class="col-right container-fluid" label-width="0px" :model="formInline">
                <div class="row">
                    <div class="col-5 course-group-list-container">
                        <!-- 课包 -->
                        <div :style="{ height: '42px', lineHeight: '42px' }">
                            <b>课程组名称</b>
                        </div>
                        <div class="course-group-list">
                            <el-scrollbar>
                                <div class=" list" v-for="v in groupedByCatebagArr" :key="v.cID"
                                    :style="{ marginTop: '6px', marginBottom: '6px' }">
                                    <div class="col text-truncate cu" @click="catebagID = Number(v.cID)"
                                        :style="{ height: '42px', lineHeight: '42px', color: catebagID === v.cID ? 'var(--color-cheng)' : '' }">
                                        {{ v.name }}
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                    </div>
                    <div class="col-7 course-list">
                        <el-form-item class="row" :style="{ height: '40px' }">
                            <!-- <el-input class="input" size="default" clearable v-model.lazy="formInline.name"
                                placeholder="输入课程名"></el-input> -->
                            <b>课程列表</b>
                        </el-form-item>
                        <el-scrollbar>
                            <!-- 课程 -->
                            <div class="list row" v-for="v in courseList" :key="v?.ID"
                                :style="{ marginTop: '6px', marginBottom: '6px' }">
                                <div class="col text-truncate" :style="{ height: '42px', lineHeight: '42px' }"
                                    :title="v?.name">
                                    {{ v?.name }}
                                </div>
                                <a target="_blank" :href="previewCourse(v)" class="router-link-q">预览</a>
                                <div class="text-center coursestyle">
                                    <span class="cu coursestylespan" @click="addclick({ ...v, catebagid: catebagID })">
                                        <el-icon color="#fff" size="18px" :style="{ transform: 'translateY(3px)' }">
                                            <Plus />
                                        </el-icon>
                                    </span>
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                </div>
                <!-- 课包分页 -->
                <!-- <div class="row">
                    <div class="col text-right">
                        <el-pagination :page-size="limit" :total="totalCount" @current-change="currentchange"
                            layout="total,prev, pager, next"
                            :current-page="Math.floor(Number(formInline._offset) / limit) + 1"></el-pagination>
                    </div>
                </div> -->
            </el-form>
        </div>
        <div class="col-5">
            <el-form class="col-right container-fluid" label-width="0px" :model="formInline">
                <div class="row" :style="{ height: '42px', lineHeight: '42px' }">
                    <div class="col">
                        <strong>已添加课程</strong>
                    </div>
                    <div class="col text-right">
                        <strong>
                            已添加：
                            <span :style="{ color: 'var(--color-cheng)' }">{{ questionid.length }}</span> 课程
                        </strong>
                    </div>
                </div>
                <div class="row">
                    <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">编号</div>
                    <div class="col" :style="{ height: '42px', lineHeight: '42px' }">名称</div>
                    <div class="text-center" :style="{ width: '80px', height: '42px', lineHeight: '42px' }">删除</div>
                </div>
                <hr :style="{ marginTop: '6px', marginBottom: '6px' }" />
                <draggable v-model="question" group="people" @start="drag = true" @end="drag = true" item-key="ID"
                    class="mydata" chosenClass="chosen">
                    <template #item="{ element, index }">
                        <div class="row" :style="{ marginTop: '6px', marginBottom: '6px' }">
                            <div :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
                                {{ element.ID }}
                            </div>
                            <div class="col text-truncate" :style="{ height: '42px', lineHeight: '42px' }">
                                {{ element.name }}
                            </div>
                            <div class="text-center" :style="{ width: '80px', height: '42px', lineHeight: '42px' }">
                                <span class="cu coursestylespan" @click="removeclick(index)">
                                    <el-icon color="#fff" size="18px" :style="{ transform: 'translateY(3px)' }">
                                        <semi-select />
                                    </el-icon>
                                </span>
                            </div>
                        </div>
                    </template>
                </draggable>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import { Plus, SemiSelect } from '@element-plus/icons-vue';
import { debounce } from 'underscore';
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import draggable from "vuedraggable";
import { useStore } from "vuex";
import { Iteamobj, asyncSelectPackageCatebagRelation, asyncselectteamcoursegroup } from '../../../api';
import { Storekey } from '../../../interface';
import Alymodel from '../../../mysql_interface/model';
import { getGroupedByCatebagArr } from '../../../util/cloudClass';
import { courseCatebag } from "../../views/data/data";
const defaultPIDs = courseCatebag.map(e => (e.pID))

const p = defineProps<{ addclick: Function, teamid: number, questionid: Alymodel.IMcourse[], change?: Function, removeclick: (i: number) => void, }>()
type E = {
    (e: 'change:questionid', value?: Alymodel.IMcourse[]): void
    (event: 'update:questionid', id: Alymodel.IMcourse[]): void
}

const store = useStore(Storekey)
const route = useRoute()
const router = useRouter()
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamId = computed(() => {
    return Number(user.value?.teamid);
});

const limit = 13
const courseGroupData = ref<Alymodel.IMcatebag[]>([])
const totalCount = ref(0)

const emit = defineEmits<E>()
const question = computed<Alymodel.IMcourse[]>({
    get() {
        return p.questionid
    },
    set(v) {
        if (p.change) {
            p.change(v)
        }
        emit('update:questionid', v)
    }
})

const formInline = reactive<Iteamobj<Alymodel.IMcourse>>({
    teamid: p.teamid
})

const drag = ref(false)

watch(formInline, () => {
    getCourse()
})
const courseList = ref<Alymodel.GroupedByCatebagPackages[]>([])
const catebagID = ref(0)
watch(() => catebagID.value, async (e) => {
    if (e) {
        getCourse()
    }
})
async function getCourse() {
    const selectedCatebag = groupedByCatebagArr.value.find(catebagItem => catebagItem.cID === catebagID.value) || { packages: [] }
    courseList.value = selectedCatebag.packages.sort((a, b) => (a.paixu || 0) - (b.paixu || 0));
}

const loading = ref(false)
const debouncet1 = ref(debouncet())
function debouncet() {
    return debounce(async () => {
        loading.value = true;
        // 获取团队代理商课包
        const { rows, count } = await asyncselectteamcoursegroup({ teamid: teamId.value })
        // 没有查到就用前端默认的7个代理商课包
        const pIds = rows?.length ? rows.map(e => Number(e.coursegroupid)) : defaultPIDs
        // 代理商课包-课程组
        await getPackageCatebagRelation(pIds)
        loading.value = false;
    }, 300);
}
// 代理商课包-课程组关系
const groupedByCatebagArr = ref<Alymodel.GroupedByCatebag[]>([])
// 获取指定代理商课包 =》 课程 =》 课程组 关系 
const teamPackageCatebagRelation = ref<Alymodel.PackageCatebagRelation[]>([])
async function getPackageCatebagRelation(pID: number[]) {
    const { rows: data, count } = await asyncSelectPackageCatebagRelation({ ID: pID, })
    totalCount.value = count
    teamPackageCatebagRelation.value = data
    // 按课程包分组
    groupedByCatebagArr.value = getGroupedByCatebagArr(data)
    // 默认选中第一个课程组
    catebagID.value = groupedByCatebagArr.value[0].cID
}

onMounted(() => {
    debouncet1.value()
})

// 
function previewCourse(v: Alymodel.GroupedByCatebagPackages) {
    const { origin, pathname } = window.location;
    let pID = JSON.stringify(v.pkg.map(e => e.pID))
    return `${origin}/ojSaas.html#/WatchCourse/${v.ID}?catebag=${catebagID.value}&ID=${v.ID}&lession=0&pID=${pID}`
}

function currentchange(r: number) {
    formInline._offset = (r - 1) * limit
}

defineExpose({
    questions: p.questionid
})

</script>

<style scoped>
.container-fluid {
    height: var(--container-height);
    background: #ffffff;
    border: 1px solid #d9d9d9;
    box-shadow: 0px 0.3px 0.9px rgba(0, 0, 0, 0.1),
        0px 1.6px 3.6px rgba(0, 0, 0, 0.13);
    border-radius: 4px;
    padding: 20px;

    --container-height: 760px;
    --container-selected-list-height: 600px;
    --container-select-list-height: 680px;
}

.input {
    display: inline-block;
    width: 45%;
}

.col-center div {
    width: 90px;
}

.icon-class-var {
    display: none;
}

.ant-bg {
    background-color: var(--color-f5);
    border-radius: 4px;
    padding-bottom: 24px;
}

.mydata {
    height: var(--container-selected-list-height);
    overflow-y: auto;
    overflow-x: hidden;
}

.mydata::-webkit-scrollbar {
    width: 0px;
    height: 1px;
}

.mydata::-webkit-scrollbar-thumb {
    border-radius: 3px;
    box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
    background: #535353;
}

.mydata::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 255, 0.3);
    border-radius: 3px;
    background: #ededed;
}

.input {
    display: inline-block;
    width: 45%;
}

.container-fluid .row {
    margin-bottom: 12px;
}

.icon-class-var {
    display: none;
}

.list {
    padding: 0 10px;
    text-align: start;
    width: 100%;
}

.list:hover .icon-class-var {
    display: inline-block;
}

.list:hover {
    color: var(--color-cheng);
    background-color: #efefef;
}

.list:hover .icon-class-var {
    display: inline-block;
}

.coursestyle {
    width: 50px;
    padding: 0;
    height: 42px;
    line-height: 42px;
}

.course-group-list-container {
    height: var(--container-select-list-height);
    border: 1px solid #eee;
}

.course-group-list {
    height: calc(var(--container-select-list-height) - 42px);
}

.course-list {
    height: calc(var(--container-select-list-height) - 40px);
}


.coursestylespan {
    width: 24px;
    height: 24px;
    background: var(--color-cheng);
    border-radius: 2px;
    display: inline-block;
    line-height: 24px;
}

.mydata .row {
    cursor: all-scroll;
}

.chosen {
    color: var(--color-cheng);
}

.router-link-q {
    width: 50px;
    padding: 0;
    height: '42px';
    line-height: 42px;
    display: block;
    color: #333;
    text-align: center;
}

.router-link-q:hover {
    color: var(--color-cheng);
}
</style>